package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
)

// BlogPost 定义了博客文章的结构
type BlogPost struct {
	Title   string `json:"title"`
	Content string `json:"content"`
	Author  string `json:"author"`
}

// blogPosts 存储了所有博客文章
var blogPosts = make([]BlogPost, 0)
var mutex sync.Mutex

func main() {
	// 静态页面路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to the Go Blog!")
	})

	// 获取所有文章
	http.HandleFunc("/posts", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			mutex.Lock()
			postsJSON, _ := json.Marshal(blogPosts)
			mutex.Unlock()
			w.Header().Set("Content-Type", "application/json")
			w.Write(postsJSON)
		default:
			w.WriteHeader(http.StatusMethodNotAllowed)
		}
	})

	// 添加新文章
	http.HandleFunc("/posts/new", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodPost:
			var newPost BlogPost
			err := json.NewDecoder(r.Body).Decode(&newPost)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			mutex.Lock()
			blogPosts = append(blogPosts, newPost)
			mutex.Unlock()
			w.WriteHeader(http.StatusCreated)
		default:
			w.WriteHeader(http.StatusMethodNotAllowed)
		}
	})

	// 监听并在8080端口启动服务器
	fmt.Println("Server is listening on port 8080...")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}
